<template>
  <div class="default-module">
    <div class="one-module">
      <div class="rev-table">
        <div class="rev-card el-card el-card__body">
          <div v-query-expand class="rev-query-form">
            <meta-grid
              v-if="pageQuery && pageQuery.grid && state.columns.length > 0"
              ref="queryMeta"
              v-model="state.conditions"
              :fields="state.columns"
              :page="pageQuery"
              :is-custom="true"
            >
              <el-button size="default" type="primary" class="ml10" @click="getList()">
                查询
              </el-button>
              <el-button size="default" class="ml10" @click="resetQuery()"> 重置 </el-button>
            </meta-grid>
          </div>
          <div class="query-tools">
            <div class="query-left">
              <el-button
                :loading="isLoading"
                type="primary"
                size="default"
                class="op-btn"
                @click="showAdd()"
              >
                新增
              </el-button>
              <!-- <el-button
                :loading="isLoading"
                type="warning"
                size="default"
                class="op-btn"
                @click="showDelete()"
              >
                删除
              </el-button> -->
            </div>
            <div class="query-right"></div>
          </div>
          <div class="main-table">
            <meta-table
              v-model:selection="state.multipleSelection"
              :list="state.list"
              :config="config.tableConfig"
              ref="mainTableRef"
              :meta="state.columns"
              :show-operation="true"
            >
              <template #operator="scope">
                <el-button link type="primary" @click.stop="showView(scope.row)"> 查看 </el-button>
                <el-button link type="primary" @click.stop="showEdit(scope.row)"> 编辑 </el-button>
                <el-button link type="primary" @click.stop="showDelete(scope.row)">
                  删除
                </el-button>
              </template>
            </meta-table>
          </div>
          <div class="table-pagination" v-if="state.source || state.total > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="state.query.page"
              :page-size="state.query.size"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              background
              :total="state.total"
            />
          </div>
        </div>
        <!-- form表单详情（查看）-->
        <el-drawer
          v-if="state.isFormReadOnly"
          size="800px"
          :title="'详情'"
          v-model="state.dialogVisible"
          @closed="dialogClose"
        >
          <meta-grid
            v-if="pageForm && pageForm.grid"
            ref="formRef"
            v-model="state.form"
            :fields="state.columns"
            :page="pageForm"
            module="form"
            :readonly="state.isFormReadOnly"
          />
          <meta-form
            v-else-if="state.dialogVisible"
            ref="formRef"
            v-model="state.form"
            :meta="state.columns"
            :readonly="state.isFormReadOnly"
          />
        </el-drawer>
        <!-- form表单详情 -->
        <Dialog
          v-else
          :title="state.form?.hasOwnProperty('id') ? '编辑' : '新增'"
          :close-on-press-escape="true"
          v-model="state.dialogVisible"
          width="50%"
          @closed="dialogClose"
        >
          <meta-grid
            v-if="pageForm && pageForm.grid"
            ref="formRef"
            v-model="state.form"
            :fields="state.columns"
            :page="pageForm"
            module="form"
            :readonly="state.isFormReadOnly"
          />
          <meta-form
            v-else-if="state.dialogVisible"
            ref="formRef"
            v-model="state.form"
            :meta="state.columns"
            :readonly="state.isFormReadOnly"
          />
          <template #footer>
            <span class="dialog-footer">
              <el-button size="default" @click="state.dialogVisible = false"> 取 消</el-button>
              <el-button type="primary" size="default" :disabled="isLoading" @click="doSave">
                保 存
              </el-button>
            </span>
          </template>
        </Dialog>
      </div>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, computed } from 'vue'
import { MetaForm, MetaTable, MetaGrid } from '@/modules/meta'
import { Dialog } from '@/modules/Dialog'
import {
  getTableMeta,
  getTableList,
  addTableData,
  getTableItem,
  editTableData,
  deleteTableData,
  auditAllTableData,
  getFormValues
} from '@/api/basic'
import { ElMessage, ElMessageBox, ElLoading as Loading } from 'element-plus'
import {
  initRemoteValues,
  initForeignValues,
  mergeFields,
  initAllValues
} from '@/modules/utils/table'
import jsyaml from 'js-yaml'
import pageYaml from './role.yaml?raw'

const pageConfig = jsyaml.load(pageYaml)

// 页面加载中...
const isLoading = ref(false)
const config = reactive({
  tableConfig: {}
})
// 查询相关参数
const state = reactive({
  source: 'table/sys_role.yaml',
  columns: pageConfig.fields, // 字段列表
  query: {
    page: 1,
    size: 10
  },
  conditions: {}, // 查询条件
  filter: '',
  order: '',
  multipleSelection: [],
  total: 0,
  list: [],
  form: {},
  dialogVisible: false,
  isFormReadOnly: false
})
// 查询条件配置
const pageQuery = computed(() => pageConfig?.query)
// form表单配置
const pageForm = computed(() => pageConfig?.form)
// relations配置
const pageRelations = ref(pageConfig?.relations)

// 查询table数据
const getList = async () => {
  isLoading.value = true
  const res = await getTableList({
    as_dict: true,
    ...state.query,
    conditions: {
      ...state.conditions
    },
    source: state.source,
    filter: state.config?.filter,
    order: state.order
  })
  isLoading.value = false
  state.list = res.data
  state.multipleSelection = []
  state.total = Number(res.count) || 0
}
// 分页查询
const handleSizeChange = (val) => {
  state.query.page = 1
  state.query.size = val
  getList()
}
// 分页查询
const handleCurrentChange = (val) => {
  state.query.page = val
  getList()
}
// 页面初始化时
const init = () => {
  getList()
}
init()

// 查询组件ref
const queryMeta = ref()
// form表单ref
const formRef = ref()
// 重置查询条件
const resetQuery = () => {
  queryMeta.value?.resetForm()
}
// 显示详情页面
const showView = (row) => {
  state.form = JSON.parse(JSON.stringify(row))
  state.isFormReadOnly = true
  state.dialogVisible = true
}
// 显示新增页面
const showAdd = () => {
  state.form = {}
  state.dialogVisible = true
}
// 弹出编辑
const showEdit = async (item) => {
  if (!item && state.multipleSelection.length < 1) {
    ElMessage({
      type: 'info',
      message: '请选择一条记录'
    })
    return
  }
  const itemData = item || state.multipleSelection[0]
  state.form = JSON.parse(JSON.stringify(itemData))
  state.isFormReadOnly = false
  state.dialogVisible = true
}
// 删除数据
const showDelete = async (item) => {
  if (!item && state.multipleSelection.length < 1) {
    ElMessage({
      type: 'info',
      message: '请选择要删除的记录'
    })
    return
  }
  ElMessageBox.confirm(`确认删除选择的记录?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const allItems = item ? [item] : state.multipleSelection
      await deleteTableData({
        id: allItems.map((t) => t.id),
        source: state.source
      })
      getList()
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
    })
    .catch(() => {})
}
// 弹框关闭时，清理数据
const dialogClose = () => {
  state.isFormReadOnly = false
}
// 保存数据
const doSave = async () => {
  const validateForm = formRef.value
  validateForm.validate(async (valid) => {
    if (valid) {
      isLoading.value = true
      if (state.form.id) {
        const res = await editTableData({
          source: state.source,
          fields: state.form
        }).finally(() => {
          isLoading.value = false
        })
        if (res === null || res === undefined) {
          return
        }
      } else {
        const res = await addTableData({
          source: state.source,
          fields: state.form
        }).finally(() => {
          isLoading.value = false
        })
        if (res === null || res === undefined) {
          return
        }
      }
      getList()
      ElMessage({ type: 'success', message: '保存成功' })
      state.dialogVisible = false
      isLoading.value = false
    }
  })
}
</script>
<style lang="less" scoped>
.rev-table {
  height: 100%;

  .table-title {
    padding-bottom: 10px;
    font-weight: bold;
  }

  .query-tools {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;

    :deep(.el-button) {
      i.el-icon {
        margin-right: 0 !important;
      }
    }

    .op-btn {
      padding: 8px 15px;

      img {
        height: 13px;
        line-height: 0;
        margin-right: 5px;
        vertical-align: middle;
      }

      .text {
        vertical-align: middle;
      }
    }

    .query-upload {
      display: inline-block;
      vertical-align: middle;
      margin-right: 10px;
      margin-left: 10px;
    }
  }

  .text-btn {
    padding: 3px 5px;
    margin-left: 0;

    img {
      height: 14px;
      vertical-align: middle;
      margin-right: 3px;
    }

    .text {
      vertical-align: middle;
    }
  }

  .table-pagination {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
